<!-- 代理商列表页面 -->
<template>
	<s-layout title="代理商" :bgStyle="{ color: '#FFF' }">
		<!-- 搜索栏 -->
		<view class="search-container">
			<view class="search-box">
				<uni-icons type="search" size="18" color="#999" />
				<input v-model="state.searchKeyword" placeholder="搜索代理商姓名或手机号" class="search-input"
					@input="onSearchInput" @confirm="onSearchConfirm" />
				<view v-if="state.searchKeyword" class="clear-btn" @click="clearSearch">
					<uni-icons type="clear" size="16" color="#999" />
				</view>
			</view>
		</view>

		<!-- 代理商列表 -->
		<view class="customer-list">
			<view v-for="(customer, index) in state.pagination.list" :key="customer.id" class="customer-item"
				@click="goToDetail(customer.id)">
				<!-- 代理商基本信息 -->
				<view class="customer-info">
					<view class="customer-header">
						<view class="customer-name">{{ customer.userName }}</view>
					</view>

					<view class="customer-details">
						<view class="detail-item" v-if="customer.mobile">
							<uni-icons type="phone" size="14" color="#666" />
							<text class="detail-text">{{ customer.mobile }}</text>
						</view>
						<view class="detail-item" v-if="customer.userType==4 && customer.agentLevel">
							<uni-icons type="auth" size="14" color="#666" />
							<text class="detail-text">{{ getUserType(customer.userType) }}
								{{ customer.userType==4 && customer.agentLevel ? getLevel(customer.agentLevel) :''}}
							</text>
						</view>
						<view class="detail-item" v-if="customer.balance">
							<uni-icons type="wallet" size="14" color="#666" />
							<text class="detail-text">{{ fen2yuan(customer.balance) }} 元</text>
						</view>
					</view>

					<view class="customer-status" v-if="customer.address">
						<uni-icons type="location" size="14" color="#666" />
						<text class="status-text">{{ customer.address }}</text>
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="customer-actions">
					<view class="action-btn edit-btn" @click.stop="editCustomer(customer.id)">
						<uni-icons type="compose" size="16" color="#007aff" />
					</view>
					<view class="action-btn edit-btn" @click.stop="recharge(customer.memberId)">
						<uni-icons type="wallet" size="16" color="#007aff" />
					</view>
					<view class="action-btn delete-btn" @click.stop="deleteCustomer(customer.id)">
						<uni-icons type="trash" size="16" color="#ff3b30" />
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="!state.loading && state.pagination.list.length === 0">
			<uni-icons type="person-add" size="60" color="#ccc" />
			<text class="empty-text">暂无代理商信息</text>
			<text class="empty-desc">点击右下角按钮添加代理商</text>
		</view>

		<!-- 加载状态 -->
		<uni-load-more v-if="state.pagination.list.length > 0" :status="state.loadStatus" :content-text="loadText"
			@clickLoadMore="loadData" />

		<!-- 添加代理商按钮 -->
		<view class="add-customer-btn" @click="addCustomer">
			<uni-icons type="plus" size="24" color="#fff" />
		</view>
		<!-- 蒙层 + 弹窗 -->
		<view v-if="showCustomModal" class="custom-modal-mask" @touchmove.stop.prevent>
			<view class="custom-modal-container">
				<!-- 弹窗内容 -->
				<view class="custom-modal-content">
					<view class="modal-header">
						<text class="modal-title">余额充值</text>
					</view>

					<view class="modal-body">
						<input class="modal-input" v-model="inputValue" type="number" placeholder="请输入充值金额"
							placeholder-class="input-placeholder" focus />
					</view>

					<view class="modal-footer">
						<view class="footer-btn cancel-btn" @click="showCustomModal = false">
							取消
						</view>
						<view class="footer-btn confirm-btn" @click="confirmInput">
							确定
						</view>
					</view>
				</view>
			</view>
		</view>
	</s-layout>
</template>

<script setup>
	import {
		fen2yuan
	} from '@/sheep/hooks/useGoods';

	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom
	} from '@dcloudio/uni-app';
	import {
		reactive,
		computed
	} from 'vue';
	import AgentApi from '@/sheep/api/agent/agent';
	import DictApi from '@/sheep/api/system/dict';
	import PayWalletApi from '@/sheep/api/pay/wallet'
	import {
		resetPagination
	} from '@/sheep/helper/utils';
	import {
		ref
	} from 'vue';

	const showCustomModal = ref(false);
	const inputValue = ref('');
	const userId = ref(0)

	const confirmInput = async () => {
		if (state.loadStatus === 'loading') return;
		if (!userId.value) {

			uni.showModal({
				title: '温馨提示',
				content: '用户尚未创建账户/或未绑定手机号，请完成后再试！',
				confirmText: '知道了',
				showCancel: false,
				success: (res) => {}
			});

			return;
		}
		if (!inputValue.value) {
			uni.showModal({
				title: '温馨提示',
				content: '请输入大于0或小于0的金额',
				confirmText: '知道了',
				showCancel: false,
				success: (res) => {}
			});

			return;
		}

		state.loadStatus = 'loading';
		try {
			let {
				code,
				data
			} = await PayWalletApi.updateWalletBalance({
				userId: userId.value,
				balance: inputValue.value * 100
			})
			if (code === 0) {
				uni.showToast({
					title: '充值成功',
					icon: 'success'
				});
				state.loadStatus = 'more';
			await onSearchConfirm();

			} else {
				throw new Error('充值失败');
			}


		} catch (error) {
			uni.showToast({
				title: '充值失败，请重试',
				icon: 'error'
			});
		} finally {
			state.loading = false;
			showCustomModal.value = false;
		}
	};

	function recharge(id) {
		inputValue.value = ''
		userId.value = id
		showCustomModal.value = true
	}
	const state = reactive({
		searchKeyword: '',
		loading: false,
		loadStatus: '',
		userTypeOptions: [],
		agentLevelOptions: [],
		pagination: {
			list: [],
			total: 0,
			pageNo: 1,
			pageSize: 10,
		},
	});

	// 加载状态文本
	const loadText = computed(() => {
		return {
			contentdown: '上拉显示更多',
			contentrefresh: '正在加载...',
			contentnomore: '没有更多数据了'
		};
	});


	// 获取代理商列表
	async function getCustomerList() {
		if (state.loadStatus === 'loading') return;

		state.loadStatus = 'loading';
		state.loading = state.pagination.pageNo === 1;

		try {
			let {
				code,
				data
			} = await AgentApi.getAgentPage({
				pageNo: state.pagination.pageNo,
				pageSize: state.pagination.pageSize,
				customerName: state.searchKeyword || undefined,
			});

			if (code !== 0) {
				throw new Error('获取代理商列表失败');
			}

			if (state.pagination.pageNo === 1) {
				state.pagination.list = data.list;
			} else {
				state.pagination.list = state.pagination.list.concat(data.list);
			}

			state.pagination.total = data.total;
			state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';

		} catch (error) {
			console.error('获取代理商列表失败:', error);
			state.loadStatus = 'noMore';

			if (state.pagination.pageNo === 1) {
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'error'
				});
			}
		} finally {
			state.loading = false;
		}
	}

	// 加载更多数据
	function loadData() {
		if (state.loadStatus === 'loading') return;

		state.pagination.pageNo++;
		getCustomerList();
	}

	// 搜索输入
	function onSearchInput(e) {
		state.searchKeyword = e.detail.value;
	}

	// 搜索确认
	async function onSearchConfirm() {
		await	resetPagination(state.pagination);
		await	getCustomerList();
	}

	// 清除搜索
	function clearSearch() {
		state.searchKeyword = '';
		resetPagination(state.pagination);
		getCustomerList();
	}

	function getLevel(val) {
		const option = state.agentLevelOptions.find(item => item.value == val);
		return option ? option.label : val;
	}

	function getUserType(val) {
		const option = state.userTypeOptions.find(item => item.value == val);
		return option ? option.label : val;
	}


	// 跳转到代理商详情
	function goToDetail(customerId) {
		uni.navigateTo({
			url: `/pages/customer/agent/detail?id=${customerId}&mode=view`
		});
	}

	// 添加代理商
	function addCustomer() {
		uni.navigateTo({
			url: '/pages/customer/agent/form?mode=add'
		});
	}

	// 编辑代理商
	function editCustomer(customerId) {
		uni.navigateTo({
			url: `/pages/customer/agent/form?id=${customerId}&mode=edit`
		});
	}

	// 删除代理商
	function deleteCustomer(customerId) {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这个代理商吗？删除后无法恢复。',
			success: async (res) => {
				if (res.confirm) {
					try {
						let {
							code
						} = await AgentApi.deleteAgent({
							id: customerId
						});
						if (code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});

							// 重新加载列表
							resetPagination(state.pagination);
							getCustomerList();
						} else {
							throw new Error('删除失败');
						}
					} catch (error) {
						console.error('删除代理商失败:', error);
						uni.showToast({
							title: '删除失败',
							icon: 'error'
						});
					}
				}
			}
		});
	}
	async function getLevelOptions() {
		try {
			let {
				code,
				data
			} = await DictApi.getDictDataListByType('agent_level');
			if (code === 0 && data) {
				state.agentLevelOptions = data;
			}
		} catch (error) {
			console.error('获取等级字典失败:', error);
		}
	}

	async function getUserTypeOptions() {
		try {
			let {
				code,
				data
			} = await DictApi.getDictDataListByType('user_type');
			if (code === 0 && data) {
				state.userTypeOptions = data;
			}
		} catch (error) {
			console.error('获取等级字典失败:', error);
		}
	}
	// 页面加载
	onLoad((options) => {

		// getCustomerList();
	});
	onShow(async () => {
		await getLevelOptions();
		await getUserTypeOptions()
		await getCustomerList();
	});

	// 下拉刷新
	onPullDownRefresh(() => {
		resetPagination(state.pagination);
		getCustomerList().then(() => {
			uni.stopPullDownRefresh();
		});
	});

	// 上拉加载更多
	onReachBottom(() => {
		if (state.loadStatus === 'more') {
			loadData();
		}
	});
</script>

<style lang="scss" scoped>
	.search-container {
		padding: 20rpx;
		background: #fff;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.search-box {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 50rpx;
		padding: 20rpx 30rpx;
		gap: 20rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;

		&::placeholder {
			color: #999;
		}
	}

	.clear-btn {
		padding: 10rpx;

		&:active {
			opacity: 0.6;
		}
	}

	.customer-list {
		padding: 20rpx;
	}

	.customer-item {
		display: flex;
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			opacity: 0.8;
		}
	}

	.customer-info {
		flex: 1;
	}

	.customer-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		gap: 20rpx;
	}

	.customer-name {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}

	.customer-gender {
		.gender-tag {
			font-size: 22rpx;
			padding: 6rpx 12rpx;
			border-radius: 20rpx;
			color: #fff;

			&.gender-male {
				background: #007aff;
			}

			&.gender-female {
				background: #ff3b30;
			}

			&.gender-unknown {
				background: #999;
			}
		}
	}

	.customer-details {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
		margin-bottom: 20rpx;
	}

	.detail-item {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.detail-text {
		font-size: 26rpx;
		color: #666;
	}

	.customer-status {
		.status-text {
			font-size: 24rpx;
			color: #999;
			background: #f8f9fa;
			padding: 8rpx 16rpx;
			border-radius: 20rpx;
			display: inline-block;
		}
	}

	.customer-actions {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-left: 20rpx;
	}

	.action-btn {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;

		&.edit-btn {
			background: rgba(0, 122, 255, 0.1);

			&:active {
				background: rgba(0, 122, 255, 0.2);
			}
		}

		&.delete-btn {
			background: rgba(255, 59, 48, 0.1);

			&:active {
				background: rgba(255, 59, 48, 0.2);
			}
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 40rpx;
		text-align: center;
	}

	.empty-text {
		font-size: 32rpx;
		color: #666;
		margin: 30rpx 0 16rpx 0;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #999;
	}

	.add-customer-btn {
		position: fixed;
		right: 40rpx;
		bottom: 100rpx;
		width: 100rpx;
		height: 100rpx;
		background: #007aff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);
		z-index: 999;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.9);
		}
	}

	/* 加载更多样式 */
	:deep(.uni-load-more) {
		padding: 30rpx 0;
	}


	/* 打开按钮样式 */
	.open-btn {
		margin: 30rpx;
		background-color: #007AFF;
		color: white;
		border-radius: 10rpx;
	}

	/* 蒙层样式 */
	.custom-modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	/* 弹窗容器 */
	.custom-modal-container {
		width: 80%;
		max-width: 600rpx;
		animation: modal-show 0.3s;
	}

	/* 弹窗内容 */
	.custom-modal-content {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
	}

	/* 弹窗头部 */
	.modal-header {
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	/* 弹窗主体 */
	.modal-body {
		padding: 40rpx 30rpx;
	}

	.modal-input {
		height: 80rpx;
		padding: 0 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 28rpx;
	}

	.input-placeholder {
		color: #999;
		font-size: 28rpx;
	}

	/* 弹窗底部按钮 */
	.modal-footer {
		display: flex;
		border-top: 1rpx solid #f5f5f5;
	}

	.footer-btn {
		flex: 1;
		text-align: center;
		padding: 25rpx 0;
		font-size: 30rpx;
	}

	.cancel-btn {
		color: #666;
		border-right: 1rpx solid #f5f5f5;
	}

	.confirm-btn {
		color: #007AFF;
		font-weight: bold;
	}

	/* 动画效果 */
	@keyframes modal-show {
		from {
			opacity: 0;
			transform: translateY(-50px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>
